package dao.impl;

import java.util.UUID;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.springframework.stereotype.Component;

import pojo.User;
import dao.UserDao;

@Component(value="JAPdao")
public class UserDaoJPA implements UserDao{
	public UserDaoJPA() {
		System.out.println("JPADao");
	}
	
	@Resource(name="manager")
	private EntityManager entityManager;

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public User addUser(User user) {
		EntityTransaction tx = entityManager.getTransaction();
		try {
			user.setId(UUID.randomUUID().toString());
			tx.begin();
			entityManager.persist(user);
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return null;
		}
		return user;
	}

	@Override
	public User findByName(String name, String pwd) {
		Query query=entityManager.createQuery("from User where uname='"+name+"' and pwd='"+pwd+"'");
		
		if(query.getResultList().size()==0){
			return null;
		}else{
			User user = (User) query.getSingleResult();
			System.out.println("jpa:" + user);
			return user;
		}
	}

}
